#include <iostream>
using namespace std;
#include <string>
#include <memory>
#include <sstream>
#include "jsoncpp/json/json.h"

bool Serialize(Json::Value &value, string &body)
{
    stringstream out;
    Json::StreamWriterBuilder swb;
    unique_ptr<Json::StreamWriter> wb(swb.newStreamWriter());
    int n = wb->write(value, &out);
    if (n != 0)
    {
        cout << "wb->write failed" << endl;
        return false;
    }
    body = out.str();
    
    return true;
}

bool Unserialize(string& body, Json::Value& value)
{
    Json::CharReaderBuilder crb;
    unique_ptr<Json::CharReader> cr(crb.newCharReader());
    string errors;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &value, &errors);
    if (ret == false)
    {
        cout << "cr->parse failed : " << errors << endl;
        return false;
    }
    return true;
}

int main()
{
    const string name = "吴小狗";
    int age = 21;
    const string sex = "男";
    vector<float> score = {89, 77.5, 93.5};

    Json::Value student;

    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);

    string body;
    Serialize(student, body);

    // cout << body << endl;

    Json::Value stu2;
    string str = R"({"姓名" : "吴大名", "年龄" : 21, "性别" : "男", "成绩" : [89.5, 77.5, 93]})";
    Unserialize(str, stu2);
    cout << "姓名 : " << stu2["姓名"].asString() << endl;
    cout << "年龄 : " <<  stu2["年龄"].asInt() << endl;
    cout << "性别 : " <<  stu2["性别"].asString() << endl;
    int sz = stu2["成绩"].size();
    for (int i = 0; i < sz; i++)
    {
        cout << "成绩 : " <<  stu2["成绩"][i].asFloat() << endl;
    }

    return 0;
}